/**
 * @author 陈泰来
 * @version V1.0
 * @Project echo-java-base
 * @Title 事件委托中的事件对象
 * @Description *
 * @Package designmodel.observe2.delegate
 * @date 2021/3/4 11:52 上午
 * @Copyright:学如逆水行舟，不进则退 .
 */
package designmodel.observe2.delegate;

import java.lang.reflect.Method;

public class Event implements IEvent {

    //单例构造
    public Event() {
    }

    public Event(Object object, String methodName, Object[] methodParams) {
        this.object = object;
        this.methodName = methodName;
        this.methodParams = methodParams;
        this.paramTypes = fillParamTypes(methodParams);
    }

    //填充参数类型
    Class[] fillParamTypes(Object[] methodParams) {
        Class[] paramTypes = new Class[methodParams.length];
        for (int i = 0; i < paramTypes.length; i++) {
            paramTypes[i] = methodParams[i] == null ? null : methodParams[i].getClass();
        }

        return paramTypes;
    }

    //事件委托对象
    private Object object;
    //委托方法名
    private String methodName;
    //方法参数
    private Object[] methodParams;
    //参数类型
    private Class[] paramTypes;

    //反射调用事件的方法
    @Override
    public void invoke() throws Exception {
        Method method = this.getObject().getClass().getMethod(this.getMethodName(), this.getParamTypes());
        method.invoke(this.getObject(), this.getMethodParams());
    }


    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public Object[] getMethodParams() {
        return methodParams;
    }

    public void setMethodParams(Object[] methodParams) {
        this.methodParams = methodParams;
    }

    public Class[] getParamTypes() {
        return paramTypes;
    }

    public void setParamTypes(Class[] paramTypes) {
        this.paramTypes = paramTypes;
    }
}
